#!/usr/bin/env python3
"""
RBAC权限系统设置脚本
"""

import os
import sys
from flask import Flask
from tools.db import create_database, init_db
from models.users import *

def setup_rbac_system():
    """设置RBAC权限系统"""
    print("🚀 设置RBAC权限系统")
    print("=" * 50)
    
    try:
        # 1. 创建数据库
        print("📊 步骤1: 创建MySQL数据库")
        if not create_database():
            print("❌ 数据库创建失败")
            return False
        print("✅ 数据库创建成功")
        
        # 2. 初始化Flask应用
        print("\n🔧 步骤2: 初始化Flask应用")
        app = Flask(__name__)
        db = init_db(app, use_mysql=True)
        print("✅ Flask应用初始化成功")
        
        # 3. 创建所有表
        print("\n📋 步骤3: 创建数据库表")
        with app.app_context():
            db.create_all()
            
            # 显示创建的表
            inspector = db.inspect(db.engine)
            tables = inspector.get_table_names()
            print(f"✅ 成功创建 {len(tables)} 个表:")
            for table in tables:
                print(f"   - {table}")
        
        # 4. 初始化基础数据
        print("\n🌱 步骤4: 初始化基础数据")
        with app.app_context():
            # 创建角色
            admin_role = Role(name='超级管理员', description='拥有所有权限')
            manager_role = Role(name='部门经理', description='管理本部门')
            employee_role = Role(name='普通员工', description='基础权限')
            
            db.session.add_all([admin_role, manager_role, employee_role])
            db.session.flush()
            
            # 创建资源
            sales_mgmt = Resource(name='销售管理', pid=0, level=1, topid=0, url='/sales', icon='el-icon-sell')
            sales_order = Resource(name='销售订单', pid=sales_mgmt.id, level=2, topid=sales_mgmt.id, url='/sales/orders', icon='el-icon-document')
            sales_add = Resource(name='销售订单新增', pid=sales_order.id, level=3, topid=sales_mgmt.id, url='/sales/orders/add', icon='el-icon-plus')
            
            product_mgmt = Resource(name='商品管理', pid=0, level=1, topid=0, url='/products', icon='el-icon-goods')
            product_add = Resource(name='新增商品', pid=product_mgmt.id, level=2, topid=product_mgmt.id, url='/products/add', icon='el-icon-plus')
            
            db.session.add_all([sales_mgmt, sales_order, sales_add, product_mgmt, product_add])
            db.session.flush()
            
            # 创建用户
            admin_user = User(username='admin', email='admin@example.com', role_id=admin_role.id)
            manager_user = User(username='manager', email='manager@example.com', role_id=manager_role.id)
            employee_user = User(username='employee', email='employee@example.com', role_id=employee_role.id)
            
            db.session.add_all([admin_user, manager_user, employee_user])
            
            # 为角色分配资源
            admin_role.res = [sales_mgmt, sales_order, sales_add, product_mgmt, product_add]
            manager_role.res = [sales_mgmt, sales_order, product_mgmt]
            employee_role.res = [sales_order]
            
            db.session.commit()
            print("✅ 基础数据初始化成功")
        
        print("\n🎉 RBAC权限系统设置完成！")
        print("📊 系统信息:")
        print("   ✅ 数据库: management_system")
        print("   ✅ 用户: root / 1234")
        print("   ✅ 主机: localhost:3306")
        print("   ✅ 字符集: utf8mb4")
        
        print("\n👥 测试用户:")
        print("   - admin (超级管理员)")
        print("   - manager (部门经理)")
        print("   - employee (普通员工)")
        
        print("\n🔗 API接口:")
        print("   - GET /api/users/ - 创建用户")
        print("   - GET /api/roles/ - 创建角色")
        print("   - GET /api/resources/ - 创建资源")
        print("   - POST /api/role-resources/ - 分配角色资源")
        print("   - GET /api/user-menu/ - 获取用户菜单")
        print("   - GET /api/init-data/ - 初始化测试数据")
        
        return True
        
    except Exception as e:
        print(f"❌ 设置失败: {str(e)}")
        return False

def test_tree_structure():
    """测试树状结构处理"""
    print("\n🌳 测试树状结构处理")
    print("=" * 30)
    
    # 测试数据
    list1 = [
        {"id": 2, 'name': '二级1', 'pid': 1, 'pname': '一级'},
        {"id": 3, 'name': '二级2', 'pid': 1, 'pname': '一级'},
        {"id": 4, 'name': '二类', 'pid': 5, 'pname': '一级5'}
    ]
    
    def convert_list(list1):
        current_dict = {}
        for i in list1:
            pid = i['pid']
            id = i['id']
            if pid not in current_dict:
                current_dict[pid] = {
                    'id': pid,
                    'name': i['pname'],
                    'son': [{'id': id, 'name': i['name']}],
                }
            else:
                current_dict[pid]['son'].append({'id': id, 'name': i['name']})
        return list(current_dict.values())
    
    result = convert_list(list1)
    print("✅ 树状结构转换成功:")
    for item in result:
        print(f"   - {item['name']}: {len(item['son'])} 个子项")
    
    return True

if __name__ == '__main__':
    success = setup_rbac_system()
    if success:
        test_tree_structure()
        print("\n🚀 系统设置完成，可以启动应用:")
        print("   python app_with_redis.py")
    else:
        print("\n❌ 系统设置失败")
        sys.exit(1)
